import os
import ctypes
import ctypes.wintypes
from .cpinfo import getwindowsencoding

HERE = os.path.dirname(os.path.abspath(__file__))
dculib = None

def load_dculib():
    global dculib
    dculib_path = os.path.join(HERE, 'dculib.dll')
    if not os.path.isfile(dculib_path):
        dculib_path = os.path.join(HERE, '..', 'dcuscan', 'dculib.dll')
    dculib = ctypes.windll.LoadLibrary(dculib_path)
    GetDeps = dculib.GetDeps
    GetDeps.restype = ctypes.wintypes.BOOL
    GetDeps.argtypes = [ctypes.c_char_p, ctypes.POINTER(ctypes.c_char_p), ctypes.POINTER(ctypes.c_char_p)]
    return dculib

def get_dcu_deps(dcufn):
    encoding = getwindowsencoding()
    if dculib is None:
        load_dculib()
    GetDeps = dculib.GetDeps
    psrcs = ctypes.c_char_p()
    pdeps = ctypes.c_char_p()
    if not GetDeps(dcufn, ctypes.byref(psrcs), ctypes.byref(pdeps)):
        raise RuntimeError("Cannot determine '%s' dependencies" % dcufn)
    srcs = [name.decode(encoding,'replace') for name in psrcs.value.splitlines()]
    deps = [name.decode(encoding,'replace') for name in pdeps.value.splitlines()]
    return srcs, deps
